<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Model\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class IndexController extends Controller
{
    //后台首页内容
    public function index()
    {
        return view('admin.index');
    }

    //后台首页 右侧内容
    public function info()
    {
        return view('admin.info');
    }

    //后台修改密码操作
    public function pass()
    {
        if($input = Input::all()) {
            //定义规则数组
            $rules = [
                'password' => 'required|between:6,20|confirmed'
            ];
            //定义错误提示信息
            $message = [
                'password.required' => '新密码不能为空!',
                'password.between' => '新密码6-20位之间!',
                'password.confirmed' => '新密码和确认密码不一致!',
            ];

            $validator = Validator::make($input, $rules, $message);

            if($validator->passes()) { //验证通过
                //1.查询当前用户的旧密码
                $uid = session('user')->user_id;
                $user_info = User::where('user_id', $uid)->first();

                //2.比较旧密码是否输入正确
                if($user_info->password == md5( md5($input['password_o']) . $user_info->salt) ) { //密码校验成功
                    //3.重新生成salt
                    $salt = rand_saltcode(); //自定义函数
                    //4.重新生成加密密码
                    $user_info->password = md5(md5($input['password']) . $salt);
                    $user_info->salt = $salt;

                    //5.更新数据库
                    $user_info->update();
                    return redirect('admin/info');

                }else { //校验失败的操作
                    return back()->with('errors', '旧密码输入有误!');
                }
            }else {
                return back()->withErrors($validator); //dd($validator->errors()->all());
            }
        }else {
            return view('admin.pass');
        }
    }
}
